{
 "cells": [
  {
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "cell_type": "code",
   "source": [
    "import osmium as o\n",
    "import geopandas as gpd\n",
    "import pandas as pd\n",
    "from shapely.geometry import LineString\n",
    "from pyproj import CRS\n",
    "\n",
    "datapath = 'datas/tokyo.osm' #对应城市的路网文件"
   ],
   "id": "6295cabce496b28d",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "class RailwayCounter(o.SimpleHandler):\n",
    "    def __init__(self):\n",
    "        super(RailwayCounter, self).__init__()\n",
    "        self.railways = []\n",
    "    \n",
    "    def way(self, w):\n",
    "        if 'railway' in w.tags:\n",
    "            self.railways.append({\n",
    "                'id': w.id,\n",
    "                'type': w.tags['railway'],\n",
    "                'name': w.tags.get('name', ''),\n",
    "                'nodes': [n.ref for n in w.nodes]\n",
    "            })"
   ],
   "id": "b002e0ff9bb203"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "class NodeCollector(o.SimpleHandler):\n",
    "    def __init__(self):\n",
    "        super(NodeCollector, self).__init__()\n",
    "        self.node_coords = {}\n",
    "    \n",
    "    def node(self, n):\n",
    "        self.node_coords[n.id] = (n.location.lon, n.location.lat)"
   ],
   "id": "807a4b5ebf17cb3e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-22T13:45:02.218955Z",
     "start_time": "2025-04-22T13:44:39.285767Z"
    }
   },
   "cell_type": "code",
   "source": [
    "handler = RailwayCounter()\n",
    "handler.apply_file(datapath)  "
   ],
   "id": "1c55717175946e43",
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-22T13:45:32.053362Z",
     "start_time": "2025-04-22T13:45:32.015837Z"
    }
   },
   "cell_type": "code",
   "source": [
    "df = pd.DataFrame(handler.railways)\n",
    "\n",
    "node_coords = {}\n",
    "\n",
    "# 收集所有节点坐标\n",
    "node_collector = NodeCollector()\n",
    "node_collector.apply_file(datapath)  \n",
    "node_coords = node_collector.node_coords\n",
    "\n",
    "# 将铁路数据转换为包含几何图形的DataFrame\n",
    "railway_features = []\n",
    "for way in handler.railways:\n",
    "    # 获取该way的所有节点坐标\n",
    "    coords = []\n",
    "    for node_id in way['nodes']:\n",
    "        if node_id in node_coords:\n",
    "            coords.append(node_coords[node_id])\n",
    "    \n",
    "    # 如果至少有2个点，创建LineString\n",
    "    if len(coords) >= 2:\n",
    "        geometry = LineString(coords)\n",
    "        railway_features.append({\n",
    "            'id': way['id'],\n",
    "            'type': way['type'],\n",
    "            'name': way['name'],\n",
    "            'geometry': geometry\n",
    "        })\n",
    "\n",
    "# 创建GeoDataFrame\n",
    "gdf = gpd.GeoDataFrame(railway_features, crs=CRS.from_epsg(4326))  # WGS84坐标系统"
   ],
   "id": "81515c30bd60ea5c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         id        type                name  \\\n",
      "0   4848751  light_rail               ゆりかもめ   \n",
      "1   4848874    monorail             東京モノレール   \n",
      "2   4848876        rail               京浜東北線   \n",
      "3   4848877        rail             JR東海道本線   \n",
      "4   4848893        rail              東海道新幹線   \n",
      "5   4848910        rail                 山手線   \n",
      "6   4848920        rail                 山手線   \n",
      "7   4848921        rail             JR東海道本線   \n",
      "8   4853663        rail             JR東海道本線   \n",
      "9   4853664        rail              東海道新幹線   \n",
      "10  4853667        rail              東海道新幹線   \n",
      "11  4853793        rail               京浜急行線   \n",
      "12  4853886  light_rail                       \n",
      "13  4853887  light_rail               ゆりかもめ   \n",
      "14  4853888  light_rail  ゆりかもめ (Yurikamome)   \n",
      "15  4853889  light_rail  ゆりかもめ (Yurikamome)   \n",
      "16  4853890  light_rail  ゆりかもめ (Yurikamome)   \n",
      "17  4853891  light_rail               ゆりかもめ   \n",
      "18  4853892  light_rail                       \n",
      "19  4853893  light_rail                       \n",
      "\n",
      "                                                nodes  \n",
      "0   [31297592, 2805871828, 6985933951, 2805871821,...  \n",
      "1                [2204524154, 6233258068, 2172443213]  \n",
      "2                              [2132993748, 31254238]  \n",
      "3                    [31254233, 2132993749, 31254232]  \n",
      "4                      [31254228, 31254229, 31254230]  \n",
      "5                              [2132993747, 31254235]  \n",
      "6   [2071138748, 2071138756, 31254243, 2071138771,...  \n",
      "7   [31254242, 2071138770, 2071138765, 31254241, 2...  \n",
      "8   [31295453, 1304285887, 1304285739, 1304285870,...  \n",
      "9                  [879879129, 1304285932, 255998911]  \n",
      "10  [31295466, 1304285903, 1304285964, 31295465, 1...  \n",
      "11  [393082148, 1304219237, 1801274994, 2212606485...  \n",
      "12  [31297624, 2431636285, 2431636354, 2431636353,...  \n",
      "13  [2805925912, 2431636252, 6985933948, 31297603,...  \n",
      "14                             [31297611, 2431636331]  \n",
      "15                               [31297601, 31297597]  \n",
      "16                               [31297600, 31297605]  \n",
      "17                             [31297604, 2431636349]  \n",
      "18  [31297642, 31297641, 5536953948, 5536953821, 5...  \n",
      "19                               [31297698, 31297699]  \n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-22T13:53:20.885007Z",
     "start_time": "2025-04-22T13:53:19.730228Z"
    }
   },
   "cell_type": "code",
   "source": "gdf.to_file(\"railways.geojson\", driver='GeoJSON')",
   "id": "f1a78b5fa12c6407",
   "outputs": [],
   "execution_count": 20
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-22T13:56:02.397038Z",
     "start_time": "2025-04-22T13:56:01.652496Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "d4d438be886c41fa",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "A module that was compiled using NumPy 1.x cannot be run in\n",
      "NumPy 2.0.2 as it may crash. To support both 1.x and 2.x\n",
      "versions of NumPy, modules must be compiled with NumPy 2.0.\n",
      "Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.\n",
      "\n",
      "If you are a user of the module, the easiest solution will be to\n",
      "downgrade to 'numpy<2' or try to upgrade the affected module.\n",
      "We expect that some modules will need time to support NumPy 2.\n",
      "\n",
      "Traceback (most recent call last):  File \"D:\\Environment\\Envs\\python3.9\\lib\\runpy.py\", line 197, in _run_module_as_main\n",
      "    return _run_code(code, main_globals, None,\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\runpy.py\", line 87, in _run_code\n",
      "    exec(code, run_globals)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel_launcher.py\", line 18, in <module>\n",
      "    app.launch_new_instance()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\traitlets\\config\\application.py\", line 1075, in launch_instance\n",
      "    app.start()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\kernelapp.py\", line 739, in start\n",
      "    self.io_loop.start()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\tornado\\platform\\asyncio.py\", line 205, in start\n",
      "    self.asyncio_loop.run_forever()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\asyncio\\base_events.py\", line 601, in run_forever\n",
      "    self._run_once()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\asyncio\\base_events.py\", line 1905, in _run_once\n",
      "    handle._run()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\asyncio\\events.py\", line 80, in _run\n",
      "    self._context.run(self._callback, *self._args)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 545, in dispatch_queue\n",
      "    await self.process_one()\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 534, in process_one\n",
      "    await dispatch(*args)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 437, in dispatch_shell\n",
      "    await result\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\ipkernel.py\", line 362, in execute_request\n",
      "    await super().execute_request(stream, ident, parent)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 778, in execute_request\n",
      "    reply_content = await reply_content\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\ipkernel.py\", line 449, in do_execute\n",
      "    res = shell.run_cell(\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\ipykernel\\zmqshell.py\", line 549, in run_cell\n",
      "    return super().run_cell(*args, **kwargs)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3024, in run_cell\n",
      "    result = self._run_cell(\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3079, in _run_cell\n",
      "    result = runner(coro)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\async_helpers.py\", line 129, in _pseudo_sync_runner\n",
      "    coro.send(None)\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3284, in run_cell_async\n",
      "    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3466, in run_ast_nodes\n",
      "    if await self.run_code(code, result, async_=asy):\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3526, in run_code\n",
      "    exec(code_obj, self.user_global_ns, self.user_ns)\n",
      "  File \"C:\\Users\\23513\\AppData\\Local\\Temp\\ipykernel_90828\\653533.py\", line 1, in <module>\n",
      "    import matplotlib.pyplot as plt\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\__init__.py\", line 109, in <module>\n",
      "    from . import _api, _version, cbook, docstring, rcsetup\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\rcsetup.py\", line 27, in <module>\n",
      "    from matplotlib.colors import Colormap, is_color_like\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\colors.py\", line 56, in <module>\n",
      "    from matplotlib import _api, cbook, scale\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\scale.py\", line 23, in <module>\n",
      "    from matplotlib.ticker import (\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\ticker.py\", line 136, in <module>\n",
      "    from matplotlib import transforms as mtransforms\n",
      "  File \"D:\\Environment\\Envs\\python3.9\\lib\\site-packages\\matplotlib\\transforms.py\", line 46, in <module>\n",
      "    from matplotlib._path import (\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "_ARRAY_API not found",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "\u001B[1;31mAttributeError\u001B[0m: _ARRAY_API not found"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "KeyboardInterrupt\n",
      "\n"
     ]
    }
   ],
   "execution_count": 23
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
